package yannan.voiplock4ble;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.List;

import butterknife.Bind;
import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.base.MyEnum;
import yannan.voiplock4ble.base.UnLoggedBaseActivity;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.bean.LockBeanDao;
import yannan.voiplock4ble.bean.UserAccount;
import yannan.voiplock4ble.bean.UserBean;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.daomanager.LockBeanDaoManager;
import yannan.voiplock4ble.db.daomanager.UserAccountDaoManager;
import yannan.voiplock4ble.db.daomanager.UserBeanDaoManager;
import yannan.voiplock4ble.task.LoginTask;
import yannan.voiplock4ble.utils.DeviceUtils;
import yannan.voiplock4ble.utils.StringEncrypt;
import yannan.voiplock4ble.utils.ToastUtils;

/**
 * 说明：登陆页面
 * 作者：mainTel
 * 时间：2016/8/19 14:10
 * 备注：
 */
@Content(R.layout.activity_login)
public class LoginActivity extends UnLoggedBaseActivity implements View.OnClickListener {

    @Bind(R.id.tv_phone)
    TextView tv_phone;
    @Bind(R.id.password)
    TextView password;
    @Bind(R.id.tv_sign_up)
    TextView tvSignUp;
    @Bind(R.id.btn_sign_in)
    public Button btn_sign_in;
    @Bind(R.id.checkbox_remeber)
    CheckBox checkBoxRemeber;
    @Bind(R.id.tv_vercode)
    TextView tvVercode;
    boolean isChecked = false;
    private UserAccount userAccount;

    @Override
    public void initData() {
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        getVersion();
        String string = "还没有账号？注册";
        SpannableString spannableString = new SpannableString(string);
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_04bfad)), 6, string.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvSignUp.setText(spannableString);
        userAccount = DaoUtils.getDao(UserAccountDaoManager.class).selectFirst();
        if (userAccount != null) {
            tv_phone.setText(userAccount.userAccount);
//            password.setText(userAccount.userPwd);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.btn_sign_in:
                login(intent);

                // 无服务器登陆
//                if (userAccount != null && (!tv_phone.getText().toString().equals(userAccount.userAccount) || !password.getText().toString().equals(userAccount.userPwd))) {
//                    ToastUtils.showToast(LoginActivity.this, "密码不正确");
//                    return;
//                }
//                UserBean bean = new UserBean();
//                bean.setUserAccount(phone);
//                bean.setUserId(phone);
//                MyApplication.getInterface().userBean = bean;
//                jump2Main();
                break;
            case R.id.tv_forget_pwd: //重置密码
                intent.setClass(mContext, RegisterActivity.class);
                intent.putExtra("isRegister", false);
                startActivity(intent);
                break;
            case R.id.tv_sign_up: //注册
                intent.setClass(mContext, RegisterActivity.class);
                intent.putExtra("isRegister", true);
                startActivity(intent);
                break;
        }
    }

    private void login(Intent intent) {
        btn_sign_in.setEnabled(false);
        String phone = tv_phone.getText().toString().trim();
        String pwd = password.getText().toString().trim();
        if (phone.equals("")) {
            tv_phone.setError("手机号不能为空");
            btn_sign_in.setEnabled(true);
            return;
        }
        if (pwd.equals("")) {
            btn_sign_in.setEnabled(true);
            password.setError("密码不能为空");
            return;
        }
        //在没网的时候判断密码是否是上次登录的正确的密码
        if (!DeviceUtils.isOnline(LoginActivity.this)) {
            if (userAccount != null && (!tv_phone.getText().toString().equals(userAccount.userAccount) || !StringEncrypt.EncryptBySHA_256(password.getText().toString()).equals(userAccount.userPwd))) {
                ToastUtils.showToast(LoginActivity.this, "当前没网且密码不正确");
                btn_sign_in.setEnabled(true);
                return;
            } else {
                MyApplication.getInterface().userBean = DaoUtils.getDao(UserBeanDaoManager.class).selectFirst();
                if (MyApplication.getInterface().userBean == null) {
                    ToastUtils.showToast(LoginActivity.this, "暂时无法连接网络并进行登录");
                    return;
                }
                // 获取本地所列表信息
                List<LockBean> lockBeans = DaoUtils.getDao(LockBeanDaoManager.class).getQueryBuilder()
                        .where(LockBeanDao.Properties.UserId.eq(MyApplication.getInterface().userBean.userId))
                        .build().list();
                intent.putExtra(MyEnum.MainEnum.lockBeanList.toString(), (Serializable) lockBeans);

                ToastUtils.showToast(LoginActivity.this, "正在离线登录");
                intent.setClass(mContext, MainActivity.class);
                startActivity(intent);
                finish();
                btn_sign_in.setEnabled(true);
            }
        } else {
            if (checkBoxRemeber.isChecked()) {
                isChecked = true;
            } else {
                isChecked = false;
            }
            LoginTask.create(this, phone, pwd, isChecked, true).start();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Object str) {
        if (str instanceof String) {
            if (str.equals("closeLoginActivity")) finish();
        }
    }

    private void jump2Main() {

        Intent intent = new Intent(mContext, MainActivity.class);
        List<LockBean> list = DaoUtils.getDao(LockBeanDaoManager.class).getQueryBuilder().where(
                LockBeanDao.Properties.UserId.eq(MyApplication.getInterface().userBean.userId)
        ).build().list();
        intent.putExtra(MyEnum.MainEnum.lockBeanList.toString(), (Serializable) list);
        mContext.startActivity(intent);
        finish();
    }

    /**
     * 获取本地的版本号
     */
    private void getVersion() {
        String versionName = "";
        try {
            versionName = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
            if (!versionName .equals("")) {
                tvVercode.setText("V" + versionName);
            }
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }
    }
}
